package com.yoke.common.interceptor;

import com.yoke.util.StringUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @author jiangzeyin
 * Created by jiangzeyin on 2017/2/4.
 */
@InterceptorUrl({"/**"})
public class LoginInterceptor extends BaseInterceptor implements GetUserName {

    public static final String SESSION_NAME = "order_user";

    public LoginInterceptor() {
        put(this);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.preHandle(request, response, handler);
        if (!(handler instanceof HandlerMethod))
            return true;
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        NotLogin notLogin = handlerMethod.getMethodAnnotation(NotLogin.class);
        if (notLogin != null)
            return true;
        String user = (String) session.getAttribute(SESSION_NAME);
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.html");
            return false;
        }
        return true;
    }

    @Override
    public String getUserName() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return (String) request.getSession().getAttribute(LoginInterceptor.SESSION_NAME);

    }

    @Override
    public String getAllUserName() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String name = (String) request.getSession().getAttribute(LoginInterceptor.SESSION_NAME);
        String vUser = (String) request.getSession().getAttribute("Visitors_User");
        String oUser = (String) request.getSession().getAttribute("Oper_User");
        return String.format("%s|%s|%s", StringUtil.convertNULL(name), StringUtil.convertNULL(vUser), StringUtil.convertNULL(oUser));
    }

}
